
import requests
from requests.sessions import Session
from retrying import retry
from fake_useragent import UserAgent

class http:
    """
    http的相关请求
    """

    def __init__(self) -> None:
        self.user_agent = UserAgent(path="user-agent.json")
        self._request = Session()

    def __enter__(self):
        self.set_request(request=self._request)
        return self

    def __exit__(self, *args):
        self._request.close()

    def set_request(self, request):
        """
        这是request的请求头等信息
        """
        request.headers.setdefault("User-Agent", self.user_agent.random)
        return request

    @retry(stop_max_attempt_number=3, stop_max_delay=1500)
    def _get(self, url, params=None, **kwargs):
        response = self._request.request(method="get", url=url, params=params, **kwargs)
        if response.status_code != 200:
            raise requests.HTTPError("")
        return response

    @classmethod
    def get(cls, url, params=None, **kwargs):
        """http的get请求"""
        with cls() as _self:
            try:
                get_method = getattr(_self, "_get")
                response = get_method(url=url, params=params, **kwargs)
            except requests.HTTPError:
                response = requests.Response()
        return response
